<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/24
 * Time: 15:48
 */

namespace Home\Controller;


use Common\Utils\Constants;
use Common\Utils\WeChatUtils;
use Home\Logic\ClientMoneyLogLogic;
use Home\Logic\MatchLogLogic;
use Home\Logic\MessageLogic;
use Home\Logic\OrderLogic;
use Home\Logic\RoomLogic;
use Home\Logic\UserLogic;
use Home\Model\Page;
use Think\Db;
use Think\Exception;

class MeController extends BaseController
{
    public function index(){
        $user = $this->getUser();
        $is_show_info = I('is_show_info','0');
        //获取未读消息数目
        $messageCount = D('MessageLog')->where(array('user_id'=>$user['id'],'status'=>0))->count();
        $goldEffect  = D('Config')->where(array('name'=>Constants::CONFIG_GOLD_EFFECT))->find();
        $earn_integral = D('Config')->where(array('name'=>Constants::CONFIG_EARN_INTEGRAL))->find();
        $goldEffectValue = html_entity_decode($goldEffect['value']);
        $earn_integral = html_entity_decode($earn_integral['value']);

//        //浏览量比例
        $proportion  = D('Config')->where(array('name'=>Constants::CONFIG_PAGEVIEWS_PROPORTION))->find();
        $proportion = $proportion['value'];
        if(is_numeric($proportion) && $proportion>0){
            $user['pageviews'] = floor($user['pageviews'] * $proportion);
        }

        $this->assign('user',$user);
        $ranking_1 = $this->getRankingByType($user['id'],Constants::MODEL_TYPE_1V1);
        $this->assign('ranking_1',$ranking_1);
        $this->assign('ranking_3',$this->getRankingByType($user['id'],Constants::MODEL_TYPE_3V3));
        $this->assign('ranking_5',$this->getRankingByType($user['id'],Constants::MODEL_TYPE_5V5));

        $this->assign('gold_content',$goldEffectValue);
        $this->assign('integral_content',$earn_integral);
        $this->assign('is_show_info',$is_show_info);
        $this->assign('messageCount',$messageCount);
        $this->display();
    }

    public function applyAgent(){
        $code = $config = D('Config')->where(array('name'=>Constants::CONFIG_APPLY_AGENT_CODE))->find();
        $this->assign('code',$code['value']);
        $this->display();
    }

    //获取当前用户排名
    private function ranking($user_id){
        $user = D('User')->where(array('id'=>$user_id))->field('total_number,win_number')->find();
        $config = D('Config')->where(array('name'=>Constants::CONFIG_SCREENINGS))->find();
        $number = $config['value'];
        if(empty($number) || !is_numeric($number)){
            $number = 10;
        }
        if($user['total_number'] < $number){
            return "未满$number 场";
        }
        $percentage = $user['win_number'] / $user['total_number'];
        $map['total_number'] = array('egt',$number);
        $map['(win_number/total_number)'] = array('gt',$percentage);
        return D('User')->where($map)->count() + 1;
    }

    private function getRankingByType($user_id,$type){
        $ranking = D('Ranking')->where(array('user_id'=>$user_id,'type'=>$type))->field('total_number,win_number')->find();
        $config = D('Config')->where(array('name'=>Constants::CONFIG_SCREENINGS))->find();
        $number = $config['value'];
        if(empty($number) || !is_numeric($number)){
            $number = 10;
        }
        $percentage = $ranking['win_number'] / $ranking['total_number'];
        $ranking['percentage'] = round($percentage * 100,2);
        if($ranking['total_number'] < $number){
            $ranking['ranking'] = "未满$number 场";
            return $ranking;
        }
        $map['total_number'] = array('egt',$number);
        $map['type'] = $type;
        $map['(win_number/total_number)'] = array('gt',$percentage);
        $ranking['ranking'] = D('Ranking')->where($map)->count() + 1;
        return $ranking;
    }


    public function rankingTest(){
        $user_id = 2557;
        echo  $this->ranking($user_id);
    }

    /**
     * 跳转到钻石作用界面
     */
    public function integralEffect(){
        $integralEffect = $config = D('Config')->where(array('name'=>Constants::CONFIG_INTEGRAL_EFFECT))->find();
        $integralEffectValue = html_entity_decode($integralEffect['value']);
        $this->assign('content',$integralEffectValue);
        $this->display();
    }

    /**
     * 跳转到比赛记录
     */
    public function matchLog(){
        $user_id = I('user_id');
        $this->assign('user_id',$user_id);
        $this->display();
    }

    /**
     * 跳转到资金流动记录
     */
    public function moneyLog(){
        $this->display();
    }

    /**
     * 跳转到领取记录界面
     */
    public function order(){
        $this->display();
    }

    /**
     * 跳转到客服二维码界面
     */
    public function customerCode(){
        $config = D('Config')->where(array('name'=>Constants::CONFIG_CUSTOMER_QR_CODE))->find();
        $this->assign('qr_code',$config['value']);
        $this->display();
    }

    /**
     * 跳转到我的代理界面 显示我的所有直推人
     */
    public function myAgent(){
        $user_id = I('user_id');
        $user = $this->getUser();
        if(empty($user_id)){
            $user_id = $user['id'];
        }
        $sourceUser = D('User')->where(array('id'=>$user_id))->field('nickname,income,total_withdraw')->find();
        $this->assign('user_id',$user_id);
        $this->assign('current_user_id',$user['id']);
        $this->assign('nickname',$sourceUser['nickname']);
        $this->assign('income',$sourceUser['income']);
        $this->assign('total_withdraw',$sourceUser['total_withdraw']);
        $this->display();
    }

    /**
     * 显示我的消息界面
     */
    public function messageLog(){
        $this->display();
    }

    /**
     * 跳转到设置界面
     */
    public function settings(){
        $this->display();
    }

    /**
     * 推广二维码
     */
    public function pushCode(){
        $show = $config = D('Config')->where(array('name' => Constants::CONFIG_PROMOTION_SHOW))->find();
        $code_bg = $config = D('Config')->where(array('name'=>Constants::CONFIG_PROMOTION_CODE_BG))->find();
        $show = html_entity_decode($show['value']);

        $user = $this->getUser();
//        if($user['user_type'] == Constants::USER_TYPE_AGENT){
            //显示用户浏览量信息
            $logic = new UserLogic();
            $pageviews = $logic->getUserPageViews($user['id']);
            $show_pageviews =$pageviews['show_pageviews'];
            $money =$pageviews['money'];
//        }else{
//            $show_pageviews = '';
//            $money = '';
//        }

        $this->assign('show_pageviews', $show_pageviews);
        $this->assign('money', $money);

        $this->jsSDK();
        $this->assign('context', $show);
        $this->assign('code_bg', $code_bg['value']);
        $this->assign('user_id', $user['id']);
        $this->assign('is_current_user',1);
        $this->display();
    }

    public function pushCodeNew(){
        $show = $config = D('Config')->where(array('name' => Constants::CONFIG_PROMOTION_SHOW))->find();
        $code_bg = $config = D('Config')->where(array('name'=>Constants::CONFIG_PROMOTION_CODE_BG))->find();
        $show = html_entity_decode($show['value']);
        $user = $this->getUser();
        $logic = new UserLogic();
        $pageviews = $logic->getUserPageViews($user['id']);
        $show_pageviews =$pageviews['show_pageviews'];
        $money =$pageviews['money'];
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]/Home/Login/registerUI?parent_id={$user['id']}";
        $this->assign('show_pageviews', $show_pageviews);
        $this->assign('url', $url);
        $this->assign('money', $money);
        $this->assign('context', $show);
        $this->assign('code_bg', $code_bg['value']);
        $this->assign('user_id', $user['id']);
        $this->assign('is_current_user',1);
        $this->display();
    }

    /**
     * ajax 获取用户二维码
     */
    public function qrCode(){
        $user = $this->getUser();
//        var_dump($user);
        $APPID = C('APPID');
        $APPSECRET = C('APPSECRET');
        $TOKEN = C('TOKEN');
        $utils = new WeChatUtils($APPID, $APPSECRET, $TOKEN);
        $utils->getQRCode($user['id']);
    }

    /**
     * ajax获取比赛记录列表
     */
    public function ajaxMatchLogList(){
        $pagesize = 10;
        $pagenumber = I('pagenum', '1');
        $user_id = I('user_id');
        $user = $this->getUser();
        if(!empty($user_id)){
            if($user['user_type'] != Constants::USER_TYPE_AGENT){
                $this->display('ajaxMatchLogList');
                return;
            }
        }else{
            $user_id = $user['id'];
        }
        $logic = new MatchLogLogic();

        $where['t_match_log.user_id'] = $user_id;
        $where['t_match_log.opponent_id'] = $user_id;
        $where['_logic'] = 'OR';
        $map['_complex'] = $where; //and
        $map['t_match_log.status']  = Constants::MATCH_END;
        $data = $logic->getMatchLogList($map,$pagenumber,$pagesize);
        if(empty($user_id)){
            $this->assign('user_id', $user['id']);
        }else{
            $this->assign('user_id', $user_id);
        }
        $this->assign('data', $data);
        $this->display('ajaxMatchLogList');
    }


    /**
     * ajax获取交易记录列表
     */
    public function ajaxMoneyLogList(){
        $pagesize = 10;
        $pagenumber = I('pagenum', '1');
        $money_type = I('money_type');
        $logic = new ClientMoneyLogLogic();
        $user = $this->getUser();
        $where['user_id'] = $user['id'];
        if($money_type == Constants::MONEY_TYPE_INTEGRAL){
            $map['_string'] = "money_type=1 OR money_type=2";
            $where['_complex'] = $map; //and
        }else{
            $where['money_type'] = $money_type;
        }
        $data = $logic->getByConditionPage($where,$pagenumber,$pagesize);
        $this->assign('head_url', $user['head_url']);
        $this->assign('data', $data);
        $this->assign('money_type', $money_type);
        $this->display('ajaxMoneyLogList');
    }

    /**
     * ajax获取领取记录
     */
    public function ajaxOrderList(){
        $pagesize = 10;
        $pagenumber = I('pagenum', '1');
        $logic = new OrderLogic();
        $user = $this->getUser();
        $where['t_order.user_id'] = $user['id'];
//        $where['status'] =
        $data = $logic->getByConditionPage($where,$pagenumber,$pagesize);
        $this->assign('data', $data);
        $this->display('ajaxOrderList');
    }

    /**
     * ajax获取推广用户列表
     */
    public function ajaxPromotionList(){
        $user_id = I('user_id');
        $pagesize = 10;
        $pagenumber = I('pagenum', '1');
        $search = I('search');
        $map['recommend_id'] = $user_id;
        $logic = new UserLogic();
        if(!empty($search)){
            $map['id'] = $search;
            $data = $logic->getByConditionPage($map, $pagenumber, $pagesize);
        }else {
            $data = $logic->getByConditionPage($map, $pagenumber, $pagesize);
        }
        $this->assign('data', $data);
        $this->display('ajaxPromotionList');
    }

    /**
     * ajax获取消息列表
     */
    public function ajaxMessageLogList(){
        $user = $this->getUser();
        $pagesize = 10;
        $pagenumber = I('pagenum', '1');
        $map['t_message_log.user_id'] = $user['id'];
        $logic = new MessageLogic();
        $data = $logic->getByConditionPage($map,$pagenumber,$pagesize);
        $this->assign('data', $data);
        $this->display('ajaxMessageLogList');
    }

    /**
     * ajax处理消息
     */
    public function process(){
        $type = I('type');
        $id = I('id');
        if(empty($id) || ($type != 1 && $type !=2)){
            $this->ajax(false,'请勿非法提交!');
        }
        $user = $this->getUser();
        $logic = new MessageLogic();
        $status = $logic->process($user['id'],$id,$type);
        $success = false;
        switch ($status){
            case 0:
                $message = '处理失败！';
                break;
            case 1:
                $success = true;
                if($type == 1){
                    $message = '已接受！';
                }else{
                    $message = '已拒绝！';
                }
                break;
            case 2:
                $message = '对不起，该消息不存在！';
                break;
            case 3:
                $message = '对不起，您无法处理该消息！';
                break;
        }
        $this->ajax($success,$message);
    }

    /**
     * ajax获取我的摆擂或我的打擂信息
     */
    public function ajaxRoomList(){
        $pagesize = 10;
        $pagenumber = I('pagenum', '1');
        $user = $this->getUser();
        $logic = new RoomLogic();
        $data = $logic->getMyRoomList(null,$pagenumber,$pagesize,$user['id']);

        $this->assign('data', $data);
        $this->display('Room/ajaxRoomList');
    }

    /**
     * ajax申请代理
     */
    public function ajaxApplyAgent(){
        $user = $this->getUser();
        $logic = new UserLogic();
        $result = $logic->applyAgent($user['id']);
        $success = false;
        $message = '';
        $data = array();
        $code = -1;
        switch ($result['status']){
            case 0:
                $message = '申请代理失败!';
                $data = $result['error'];
                break;
            case 1:
                $message = '申请代理成功！';
                $success = true;
                break;
            case 2:
                $message = '对不起，您当前钻石数目不足！';
                $code = Constants::CODE_INTEGRAL_INSUFFICIENT;
                break;
            case 3:
                $message = '对不起，您已经申请过代理，不能重复申请！';
                break;
            case 4:
                $message = '对不起，您已经是代理，不能重复申请!';
                break;
        }
        $this->ajax($success,$message,$code,$data);
    }

    public function modifyPasswordUI(){
        $this->display('modify_password');
    }

    public function modifyPassword(){
        $old_password = I('old_password');
        $new_password = I('new_password');
        $re_password = I('re_password');
        $success = false;
        if($old_password == ''){
            $message = '请输入原密码';
            $this->ajax($success,$message);
        }
        if($new_password == ''){
            $message = '请输入新密码';
            $this->ajax($success,$message);
        }
        if($new_password != $re_password){
            $message = '密码不一致';
            $this->ajax($success,$message);
        }
        $user = $this->getUser();
        $user = M('User')->where(array('id'=>$user['id']))->field('id,register_time,password')->find();
        $old_password = md5($old_password.''.$user['register_time']);
        $new_password = md5($new_password.''.$user['register_time']);
        if($old_password != $user['password']){
            $this->ajax(false,'原密码错误');
        }
        M('User')->where(array('id'=>$user['id']))->save(['password'=>$new_password]);
        $this->ajax(true,'修改成功');
    }

    public function modifyUser(){
        $model = M();
        $model->startTrans();
        try {
            $user_list = M('User')->field('id,create_time,register_time')->select();
            foreach ($user_list as $key => $value) {
                $update['register_time'] = $value['create_time'];
                $update['password'] = md5('123456' . $update['register_time']);
                $model->table('t_user')->where(array('id' => $value['id']))->save($update);
            }
            $model->commit();
        }catch (\Exception $e){
            var_dump($e->getMessage());
        }
    }

}